package com.superc.server;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.superc.client.MySuperToolboxService;
import com.superc.server.data.NotebookItem;
import com.superc.shared.util.StringHelper;

@SuppressWarnings("serial")
public class MySuperToolboxServiceImpl extends RemoteServiceServlet implements MySuperToolboxService {

	public String getUserName() {
		PersistenceManager pm = StorageManager.get().getPersistenceManager();
	    String result="";
		try{
		    String query = "select from " + NotebookItem.class.getName();
		    @SuppressWarnings("unchecked")
			List<NotebookItem> greetings = (List<NotebookItem>) pm.newQuery(query).execute();

		    for (NotebookItem notebookItem : greetings) {
				result+=notebookItem.getName();
			}
		}
		finally{
			pm.close();
		}
	    return result;
//		UserService userService=UserServiceFactory.getUserService();
//		User user=userService.getCurrentUser();
//		if (user!=null){
//			return user.getNickname();
//		}
//		else{
//			return userService.createLoginURL(
//		       getThreadLocalRequest().getRequestURI());
//		}
		
		
	}

	@Override
	public String addNotebookItem(String text,String content, String catelog, Date startTime,
			Date endTime) {
		NotebookItem item=new NotebookItem(StringHelper.SubString(text,0,400), content,catelog,startTime,endTime,Calendar.getInstance().getTime());
		StorageManager.makePersistent(item);
		return null;
	}

	@Override
	public com.superc.client.data.NotebookItem[] getNotebookItem(String catelog, int startIndex, int endIndex) {
		PersistenceManager pm = StorageManager.get().getPersistenceManager();
	    try{
		    String query = "select from " + NotebookItem.class.getName();
		    @SuppressWarnings("unchecked")
			List<NotebookItem> notebookItems = (List<NotebookItem>) pm.newQuery(query).execute();
		    if(notebookItems.size()>0){
		    	NotebookItem[] resultServer= new NotebookItem[notebookItems.size()];
		    	notebookItems.toArray(resultServer);
		    	return cloneNotebookItem(resultServer);
		    }
		    else
		    	return null;
		}
		finally{
			pm.close();
		}
	}

	
	
	private com.superc.client.data.NotebookItem[] cloneNotebookItem(NotebookItem[] serverItems){
		com.superc.client.data.NotebookItem[] results=new com.superc.client.data.NotebookItem[serverItems.length];
		for (int i = 0; i < serverItems.length; i++) {
			results[i]=new com.superc.client.data.NotebookItem(serverItems[i].getName(),
					serverItems[i].getContent(),serverItems[i].getCatelog(),serverItems[i].getStartTime(),
					serverItems[i].getEndTime(),serverItems[i].getCreateTime());
			results[i].setId(serverItems[i].getId());
		}
		return results;
	}
}
